package org.smartboot.flow.spring.extension;

import org.smartboot.flow.core.parser.ParserContext;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;

/**
 * @author qinluo
 * @date 2023/3/12 12:41
 * @since 1.0.0
 */
public class SmartFlowBeanFactoryRegistry implements BeanDefinitionRegistryPostProcessor {

    private BeanDefinitionRegistry registry;

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
        this.registry = registry;
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        try {
            // Touch visit all parsed elements after all bean definition loaded.
            ParserContext ctx = ProxyParser.getInstance().getContext();
            if (ctx != null) {
                // Load script inside xml.
                ctx.getScriptLoaders().forEach(p -> p.load(ctx));
                BeanDefinitionVisitor visitor = new BeanDefinitionVisitor(registry, ctx);
                ctx.getRegistered().forEach(visitor::visit);
            }
        } finally {
            ProxyParser.getInstance().reset();
        }
    }
}
